package com.zk.web;

import com.zk.model.Blog;
import com.zk.model.Discuss;
import com.zk.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    @GetMapping("/{page}")
    public String page(@PathVariable String page){
        log.info("returning to {}", page);
        return page + ".html";
    }

    @GetMapping("/")
    public String index(@RequestParam(required = false, defaultValue = "1") Integer pageNumber,
                        @RequestParam(required = false, defaultValue = "5") Integer pageSize,
                        @RequestParam(required = false) String keywords,
                        HttpServletRequest request
    ){
        log.info("returning to index ");
        PageQuery<Blog> pageBlog = blogService.queryBlog(keywords, pageNumber, pageSize);
        request.setAttribute("pageBlog", pageBlog);
        return "index.html";
    }

    @PostMapping("/editor")
    public String edit(Blog blog){
        blogService.saveBlog(blog);
        return "redirect:/";
    }

    @GetMapping("/single")
    public String single(Integer id,
                         @RequestParam(required = false, defaultValue = "1") Integer pageNumber,
                         @RequestParam(required = false, defaultValue = "5") Integer pageSize,
                         HttpServletRequest request){
        Blog blog = blogService.queryOneBlog(id);
        PageQuery<Discuss> pageDiscuss = blogService.queryDiscuss(id, pageNumber, pageSize);
        request.setAttribute("blog", blog);
        request.setAttribute("pageDiscuss", pageDiscuss);
        return "single.html";
    }

    @PostMapping("/discussEditor")
    public String editDiscuss(Discuss discuss){
        blogService.saveDiscuss(discuss);
        return "redirect:/single?id="+ discuss.getBlogId();
    }

    @GetMapping("/archive")
    public String editDiscuss(HttpServletRequest request){
        List<String> archiveList = blogService.queryBlogGroupByMonth();
        request.setAttribute("archiveList", archiveList);
        return "common/_aside.html#archiveList";
    }
}
